package com.zhh.front.controller;

import com.zhh.api.model.BidInfo;
import com.zhh.api.model.IncomeRecord;
import com.zhh.api.model.User;
import com.zhh.api.pojo.UserAccountInfo;
import com.zhh.api.service.SmsService;
import com.zhh.api.service.UserService;
import com.zhh.common.enums.RCode;
import com.zhh.common.util.CommonUtil;
import com.zhh.common.util.JwtUtil;
import com.zhh.front.service.RealnameServiceImpl;
import com.zhh.front.view.Realname;
import com.zhh.front.view.RespResult;
import com.zhh.front.view.center.IncomeResultView;
import com.zhh.front.view.center.InvestResultView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户功能")
@RequestMapping("/v1/user")
public class UserController extends BaseController {

    @Resource(name = "smsCodeRegisterImpl")
    private SmsService registerSmsService;

    @Resource(name = "smsCodeLoginImpl")
    private SmsService loginSmsService;

    @Resource
    private RealnameServiceImpl realnameService;

    //手机号是否注册
    @ApiOperation(value = "查看手机号是否注册", notes = "在注册功能中，手机号是否可以注册")
    @ApiImplicitParam(name = "phone", value = "手机号")
    @GetMapping("/phone/exists")
    public RespResult phoneExists(@RequestParam("phone") String phone) {
        RespResult result = RespResult.fail();
        //检查手机号是否符合要求
        if (CommonUtil.checkPhone(phone)) {
            User user = userService.queryByPhone(phone);
            if (user == null) {
                //该手机号没有查到用户，该手机号可以注册
                result = RespResult.ok();
            } else {
                result.setRCode(RCode.PHONE_EXISTS);
            }
        } else {
            result.setRCode(RCode.PHONE_FORMAT_ERR);
        }
        return result;
    }

    //注册
    @ApiOperation(value = "用户注册功能")
    @PostMapping("/register")
    public RespResult userRegister(@RequestParam String phone,
                                   @RequestParam String pword,
                                   @RequestParam String scode) {
        RespResult result = RespResult.fail();
        //检查参数
        if (CommonUtil.checkPhone(phone)) {
            if (pword != null && pword.length() == 32) {
                //检查验证码是否正确
                if (registerSmsService.checkSmsCode(phone, scode)) {
                    //验证码正确，可以注册
                    int registerResult = userService.userRegister(phone, pword);
                    if (registerResult == 1) {
                        result = RespResult.ok();
                    } else if (registerResult == 2) {
                        result.setRCode(RCode.PHONE_EXISTS);
                    } else {
                        result.setRCode(RCode.REQUEST_PARAM_ERR);
                    }
                } else {
                    result.setRCode(RCode.SMS_CODE_INVALID);
                }
            } else {
                result.setRCode(RCode.REQUEST_PARAM_ERR);
            }
        } else {
            result.setRCode(RCode.PHONE_FORMAT_ERR);
        }
        return result;
    }

    //登录
    @ApiOperation(value = "用户登录-获取访问token")
    @PostMapping("/login")
    public RespResult userLogin(@RequestParam String phone,
                                @RequestParam String pword,
                                @RequestParam String scode) throws Exception {
        RespResult result = RespResult.fail();
        if (CommonUtil.checkPhone(phone) && (pword != null && pword.length() == 32)) {
            //发送验证码
            if (loginSmsService.checkSmsCode(phone, scode)) {
                //用户登录
                User user = userService.userLogin(phone, pword);
                if (user != null) {
                    //登录成功，生成token
                    Map<String, Object> data = new HashMap<>();
                    data.put("uid", user.getId());
                    //token中携带用户的id属性
                    String jwtToken = JwtUtil.createJwt(data, 120);

                    //返回给前端用户的信息
                    Map<String, Object> userInfo = new HashMap<>();
                    userInfo.put("uid", user.getId());
                    userInfo.put("phone", user.getPhone());
                    userInfo.put("name", user.getName());

                    //成功
                    result = RespResult.ok();
                    result.setAccessToken(jwtToken);
                    result.setData(userInfo);
                } else {
                    result.setRCode(RCode.PHONE_LOGIN_PASSWORD_INVALID);
                }
            } else {
                result.setRCode(RCode.SMS_CODE_INVALID);
            }
        } else {
            result.setRCode(RCode.REQUEST_PARAM_ERR);
        }
        return result;
    }


    //实名认证
    @ApiOperation(value = "实名认证")
    @PostMapping("/realname")
    public RespResult userRealname(@RequestBody Realname realname) {
        RespResult result = RespResult.fail();
        //验证请求参数
        if (CommonUtil.checkPhone(realname.getPhone()) && StringUtils.isNotBlank(realname.getName()) && StringUtils.isNotBlank(realname.getIdCard())) {

            //判断用户是否已经完成实名认证
            User user = userService.queryByPhone(realname.getPhone());
            if (user != null) {
                if (StringUtils.isNotBlank(user.getName())) {
                    result.setRCode(RCode.REALNAME_RETRY); //已经实名认证过

                } else {
                    //没有实名认证过，调用第三方实名认证接口
                    int realnameResult = realnameService.handleRealname(realname.getPhone(), realname.getName(), realname.getIdCard());

                    if (realnameResult == 1) {
                        result = RespResult.ok(); //成功
                    } else if (realnameResult == 2) {
                        result.setRCode(RCode.REALNAME_FAIL);
                    }
                }
            } else {
                result.setRCode(RCode.REQUEST_PARAM_ERR);
            }
        }
        return result;
    }

    //用户中心
    @ApiOperation(value = "用户中心")
    @GetMapping("/usercenter")
    public RespResult userCenter(@RequestHeader(value = "uid",required = false) Integer uid){
        RespResult result  = RespResult.fail();
        //检查数据是否正确
        if( uid != null && uid > 0 ){
            //调用数据库，查询用户数据
            UserAccountInfo userAccountInfo = userService.queryUserAllInfo(uid);
            if( userAccountInfo != null ){
                //查询成功
                result = RespResult.ok();
                //把数据返回给前端
                Map<String,Object> data = new HashMap<>();
                data.put("name",userAccountInfo.getName()); //名字
                data.put("phone",userAccountInfo.getPhone()); //手机号
                data.put("headerUrl",userAccountInfo.getHeaderImage()); //头像
                data.put("money",userAccountInfo.getAvailableMoney()); //余额
                if( userAccountInfo.getLastLoginTime() != null){ //登录时间
                    data.put("loginTime", DateFormatUtils.format(
                            userAccountInfo.getLastLoginTime(),"yyyy-MM-dd HH:mm:ss"));
                } else  {
                    data.put("loginTime","-");
                }
                result.setData(data);
            }
        }
        return result;
    }

    //获取用户和收益信息
    @ApiOperation(value = "获取收益信息")
    @GetMapping("/income/records")
    public RespResult queryInvestPage(@RequestHeader("uid") Integer uid,
                                      @RequestParam(required = false,defaultValue = "1") Integer pageNo,
                                      @RequestParam(required = false,defaultValue = "6") Integer pageSize){
        RespResult result = RespResult.fail();

        //数据验证
        if(uid != null && uid > 0) {
            //数据库中取出充值记录
            List<IncomeRecord> records = userService.queryByUid(uid,pageNo,pageSize);
            //成功
            result = RespResult.ok();
            //把RechargeRecord类转换成RechargeResultView视图类
            result.setList(toView(records));
        }
        return result;
    }


    private List<IncomeResultView> toView(List<IncomeRecord> src){
        List<IncomeResultView> target = new ArrayList<>();
        src.forEach( record -> {
            target.add( new IncomeResultView(record.getId(),
                    productService.queryTypeById(record.getLoanId()),
                    record.getIncomeDate(),
                    record.getIncomeMoney()));
        });
        return target;
    }
}







